﻿<%@ Control Language="C#" AutoEventWireup="true" Inherits="App_Code.Modules.BookModule" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="Portal.Core.Binding" %>
<%@ Import Namespace="Portal.Core.Helper" %>
<%@ Import Namespace="Portal.Core.Utils" %>
<%@ Import Namespace="Portal.Data.Entity" %>
<%@ Register TagPrefix="telerik" Namespace="Telerik.Web.UI" Assembly="Telerik.Web.UI" %>
<%@ Register Assembly="Portal.Core" Namespace="Portal.Core.Web.UI.Controls" TagPrefix="cc1" %>
<asp:PlaceHolder runat="server" ID="phContent">
    <div class="filter">
        <h3>Sửa truyện</h3>
    </div>
    <table class="Form">
        <tr>
            <td style="width: 15%">Thể loại
            </td>
            <td>
                <asp:ListBox ID="HistyoryIds" Height="200" runat="server" DataValueField="Id" DataTextField="FullName" SelectionMode="Multiple"></asp:ListBox>
            </td>
        </tr>
        <tr>
            <td style="width: 15%">Tác giả
            </td>
            <td>
                <asp:TextBox runat="server" ID="author" Width="250"></asp:TextBox>
                <em>(Gõ vào ô text để tìm chính xác tác giả, hoặc tạo mới nếu chưa tồn tại)</em>
            </td>
        </tr>
        <tr>
            <td>Tiêu đề <span class="red bold">(*)</span>
            </td>
            <td>
                <asp:TextBox ID="FullName" runat="server" Width="90%"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td>SortName
            </td>
            <td>
                <asp:TextBox ID="SortName" runat="server" Width="90%"></asp:TextBox>
            </td>
        </tr>
        
        <tr>
            <td>Tiêu đề khác
            </td>
            <td>
                <asp:TextBox ID="OtherName" runat="server" Width="90%"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td>OtherSortName
            </td>
            <td>
                <asp:TextBox ID="OtherSortName" runat="server" Width="90%"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td>Mô tả
            </td>
            <td>
                <telerik:RadEditor ID="Description" runat="server" ToolsFile="~/cms_client/Editor_Rad_Full.xml" Height="350" Width="99%">
                </telerik:RadEditor>
            </td>
        </tr>
        <tr>
            <td>Ảnh
            </td>
            <td>
                <cc1:ImageUpload ID="imgUpload" runat="server" />
            </td>
        </tr>
        <tr>
            <td></td>
            <td>
                <asp:CheckBox ID="Status" Text="Kích hoạt?" runat="server" Checked="true" />
                <asp:CheckBox ID="IsUnique" Text="Duy nhất?" runat="server" Checked="true" />
                <asp:CheckBox ID="IsHot" Text="Truyện HOT?" runat="server" />
                <asp:CheckBox ID="Finish" Text="Đã kết thúc?" runat="server" />
            </td>
        </tr>
        <tr>
            <td colspan="2">---------- Other Info ------------------------------------------------------------------------------------------------</td>
        </tr>
        <tr>
            <td>Thời gian</td>
            <td>
                <table>
                    <tr>
                        <td style="white-space: nowrap">Ngày tạo<br />
                            <cc1:DatePicker runat="server" ID="CreatedDate" ShowTime="True" />
                        </td>
                        <td style="width: 20px;"></td>
                        <td style="white-space: nowrap">Ngày sửa<br />
                            <cc1:DatePicker runat="server" ID="ModifiedDate" ShowTime="True" />
                        </td>
                    </tr>
                </table>
            </td>
        </tr>
        <tr>
            <td>Tổng chương</td>
            <td>
                <asp:TextBox ID="TotalChap" runat="server" Width="100"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td>Chương cuối</td>
            <td>
                <asp:TextBox ID="LastChapId" runat="server" Width="100"></asp:TextBox>
                <asp:Label ID="lblLastChap" runat="server"></asp:Label>
            </td>
        </tr>
        <tr>
            <td>Visited</td>
            <td>
                <asp:TextBox ID="Visited" runat="server" Width="100"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td>Rate Average</td>
            <td>
                <asp:TextBox ID="RateAverage" runat="server" Width="100"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td>Rate Total</td>
            <td>
                <asp:TextBox ID="RateTotal" runat="server" Width="100"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td colspan="2">---------- SEO ------------------------------------------------------------------------------------------------</td>
        </tr>
        <tr>
            <td>MetaTitle</td>
            <td>
                <asp:TextBox ID="MetaTitle" runat="server" Width="90%" Rows="2" TextMode="MultiLine"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td>MetaDesc</td>
            <td>
                <asp:TextBox ID="MetaDesc" runat="server" Width="90%" Rows="2" TextMode="MultiLine"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td>MetaKeyword</td>
            <td>
                <asp:TextBox ID="MetaKeyword" runat="server" Width="90%" Rows="2" TextMode="MultiLine"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td>Tags</td>
            <td>
                <asp:TextBox ID="Tags" runat="server" Width="90%"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td>Real Url</td>
            <td>
                <asp:Label ID="Url" runat="server"></asp:Label>
            </td>
        </tr>
        <tr>
            <td colspan="2">---------- Crawl Info ------------------------------------------------------------------------------------------------</td>
        </tr>
        <tr>
            <td>Nguồn</td>
            <td>
                <asp:TextBox ID="Source" runat="server"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td>CrawlName</td>
            <td>
                <asp:TextBox ID="CrawlName" runat="server" Width="90%"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td>CrawlHost</td>
            <td>
                <asp:TextBox ID="CrawlHost" runat="server"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td>CrawlAuthor</td>
            <td>
                <asp:TextBox ID="CrawlAuthor" runat="server"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td>CrawlUrl</td>
            <td>
                <asp:TextBox ID="CrawlUrl" runat="server" Width="90%"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td></td>
            <td>
                <br />
                <asp:Button ID="Save" runat="server" Text="Lưu lại" Width="150" OnClick="Save_Click" OnClientClick="return checkValid();" />
                <asp:Button ID="Cancel" runat="server" OnClick="Cancel_Click" Text="Bỏ qua" ValidationGroup="xxxx" />
                <asp:Button ID="Delete" runat="server" CssClass="CommandDelete" OnClick="Delete_Click"
                    OnClientClick="return confirmDelete();" ValidationGroup="xxxx" ToolTip=" Xóa " />
            </td>
        </tr>
    </table>
</asp:PlaceHolder>

<script type="text/javascript">
    $(function () {
        $("#<%=author.ClientID%>").autocomplete({
            source: function (request, response) {
                $.ajax({
                    url: "/Ajax.aspx",
                    dataType: "json",
                    data: { p: "Author", act: "find", key: request.term },
                    success: function (data) {
                        response(data.label);
                    }
                });
            }
        });
    });
    function checkValid() {
        var types = $('#<%=HistyoryIds.ClientID %>');
        if (types.val() == null) {
            alert("Hãy chọn thể loại truyện!");
            types.focus();
            return false;
        }
        var author = jQuery('#<%=author.ClientID %>');
        if (author.val() == null) {
            alert("Hãy chọn tác giả!");
            author.focus();
            return false;
        }
        var fullname = jQuery('#<%=FullName.ClientID %>');
        if (fullname.val().length == 0) {
            alert("Hãy điền tiêu đề!");
            fullname.focus();
            return false;
        }
        return true;
    }
</script>

<script runat="server">
    protected override string Action
    {
        get
        {
            return "edit";
        }
    }
    protected override Control Root
    {
        get
        {
            return phContent;
        }
    }
    private Book _currentObj, _editBook;
    protected Book EditBook
    {
        get
        {
            if (_editBook == null)
            {
                object obj = Portal.Core.Binding.Binder.GetData(_currentObj, phContent, new BindContext());
                if (obj != null)
                {
                    _editBook = (Book)obj;
                }
            }
            return _editBook;
        }
    }
    protected override void OnInit(EventArgs e)
    {
        if (!IsPostBack)
        {
            SetRadEditorPlugin(Description);

            HistyoryIds.DataSource = HistoryType.ListAll();
            HistyoryIds.DataBind();
        }

        _currentObj = (Book)FindByPrimaryKey();
        Binder.SetData(phContent, _currentObj, new BindContext());

        if (!IsPostBack)
        {
            //binding some
            var selecteds =
                (_currentObj.HistoryTypeIds ?? "").Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(
                    x => Convert.ToInt32(x)).ToArray();
            if (selecteds.Any())
            {
                foreach (int sel in selecteds)
                {
                    HistyoryIds.Items.FindByValue(sel.ToString()).Selected = true;
                }
            }

            // other info
            Url.Text = _currentObj.Url;
            var lastchap = _currentObj.LastChap;
            if (lastchap != null)
            {
                lblLastChap.Text = _currentObj.LastChapTitle;
            }

            var auth = Author.FindByPrimaryKey(_currentObj.AuthorId);
            if (auth != null)
                author.Text = auth.FullName;
            imgUpload.LastUpload = _currentObj.Image;
        }
    }

    void SetRadEditorPlugin(RadEditor editor)
    {
        editor.DisableFilter(EditorFilters.ConvertCharactersToEntities | EditorFilters.RemoveScripts);
        editor.EditModes = EditModes.Design | EditModes.Html;
        editor.StripFormattingOptions = EditorStripFormattingOptions.MSWord |
                                        EditorStripFormattingOptions.MSWordNoFonts |
                                        EditorStripFormattingOptions.Css |
                                        EditorStripFormattingOptions.Font |
                                        EditorStripFormattingOptions.Span |
                                        EditorStripFormattingOptions.ConvertWordLists;
    }
    protected override void Save_Click(object sender, EventArgs e)
    {
        //set types
        var typeIds = HistyoryIds.Items.OfType<ListItem>().Where(item => item.Selected).Select(x => Convert.ToInt32(x.Value)).ToArray();
        BookType.ChangedType(EditBook.ID, typeIds);    //execute by sql command
        EditBook.HistoryTypeIds = string.Join(",", typeIds);

        //check image, and upload to google
        if (imgUpload.HasFile)
        {
            //upload:
            var savePath = "Files/Book/";
            if (!Directory.Exists(FileHelper.GetPhysicalPath(savePath)))
                Directory.CreateDirectory(FileHelper.GetPhysicalPath(savePath));

            savePath += Guid.NewGuid().ToString();
            string fname = imgUpload.PostedFile.FileName;
            savePath += fname.Substring(fname.IndexOf("."), fname.Length - fname.IndexOf("."));
            imgUpload.Save(savePath);

            EditBook.Image = savePath;
            if (!string.IsNullOrEmpty(EditBook.Image) && EditBook.Image.IndexOf("google") < 0)
            {
                var bloggerAcc = GoogleHelper.GetBloggerAccount();
                try
                {
                    var gInfos = GoogleHelper.UploadImageToGoogle(FileHelper.GetPhysicalPath(EditBook.Image),
                                                                  EditBook.SortName, bloggerAcc.UserName,
                                                                  bloggerAcc.Password, "truyengicungco");
                    if (gInfos.Count > 0)
                    {
                        var googleImage = gInfos["url"].ToString();
                        //remove image temps here...
                        FileHelper.Remove(EditBook.Image);
                        //set new full google path
                        EditBook.Image = googleImage;
                    }
                }
                catch
                {
                }
            }
        }
        var authorName = author.Text.Trim();
        var authSortName = Process.ConvertToSafeMarks(authorName).Replace("-", "").Trim().ToLower();
        var auth = Author.MatchedBySortName(authSortName);
        if (auth == null)
        {
            auth = new Author { FullName = authorName, SortName = authSortName };
            auth.Save();
        }
        EditBook.AuthorId = auth.ID;

        EditBook.Update();
        Forward("save");
    }

</script>
